package com.statistics.service.impl;

import com.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.statistics.client.UcenterClient;
import com.statistics.entity.Daily;
import com.statistics.mapper.DailyMapper;
import com.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-07-24
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

	@Autowired
	private UcenterClient ucenterClient;

	@Override
	public void registerCount(String day) {

		QueryWrapper<Daily> wrapper = new QueryWrapper<>();
		wrapper.eq("date_calculated",day);
		baseMapper.delete(wrapper);

		R r = ucenterClient.countRegister(day);
		Integer countRegister = (Integer) r.getData().get("countRegister");

		Daily daily = new Daily();
		daily.setRegisterNum(countRegister);
		daily.setDateCalculated(day);

		daily.setLoginNum(RandomUtils.nextInt(100, 200));
		daily.setVideoViewNum(RandomUtils.nextInt(100, 200));
		daily.setCourseNum(RandomUtils.nextInt(100, 200));

		baseMapper.insert(daily);
	}

	@Override
	public Map<String, Object> getShowData(String type, String begin, String end) {
		QueryWrapper<Daily> wrapper = new QueryWrapper<>();
		wrapper.between("date_calculated",begin,end);
		wrapper.select("date_calculated",type);
		List<Daily> staList = baseMapper.selectList(wrapper);

		//因为返回有两部分数据，日期和日期对应数量
		//前端要求数据json格式，对应后端Java代码的list集合
		//创建两个list集合，一个日期list，一个数量list
		List<String> date_calculatedList = new ArrayList<>();
		List<Integer> numDataList = new ArrayList<>();

		for (int i = 0; i < staList.size();i++){
			Daily daily = staList.get(i);
			date_calculatedList.add(daily.getDateCalculated());

			switch (type){
				case "login_num":
					numDataList.add(daily.getLoginNum());
					break;
				case "register_num":
					numDataList.add(daily.getRegisterNum());
					break;
				case "video_view_num":
					numDataList.add(daily.getVideoViewNum());
					break;
				case "course_num":
					numDataList.add(daily.getCourseNum());
					break;
				default:
					break;
			}
		}
		Map<String,Object> map = new HashMap<>();
		map.put("date_calculated",date_calculatedList);
		map.put("numDataList",numDataList);

		return map;
	}
}
